import styles from './index.module.scss'
import { NavBar, Form, Input, Button, List, Toast } from 'antd-mobile'
import { useHistory } from 'react-router-dom'
import { LoginType } from '@/types/data'
import { useDispatch } from 'react-redux'
import { getCode, login } from '@/store/actions/login'
import { useRef, useState } from 'react'
import { FormInstance } from 'antd-mobile/es/components/form'
import { InputRef } from 'antd-mobile/es/components/input'
import { useEffect } from 'react'
export default function Login() {
  const history = useHistory()
  const dispatch = useDispatch()
  // form实例
  // const [form] = Form.useForm()
  const formRef = useRef<FormInstance>(null)
  const mobileRef = useRef<InputRef>(null)
  const timeRef = useRef(-1)
  const [time, setTime] = useState(0)
  const onFinish = async (values: LoginType) => {
    await dispatch(login(values))
    history.replace('/home')
    Toast.show({
      content: '登录成功',
      icon: 'success',
    })
  }

  // 获取验证码
  const onGetCode = async () => {
    const current = formRef.current!
    const mobile = current.getFieldValue('mobile')
    const errors = current.getFieldError('mobile')
    if (!mobile || errors.length > 0) {
      // 让手机号自动获取焦点
      mobileRef.current!.focus()
      return
    }
    await dispatch(getCode(mobile))
    // 开启倒计时
    setTime(60)
    timeRef.current = window.setInterval(() => {
      setTime((time) => time - 1)
    }, 1000)
  }

  useEffect(() => {
    if (time === 0) {
      window.clearInterval(timeRef.current)
    }
  }, [time])

  // 组件销毁的时候，清理定时器
  useEffect(() => {
    return () => {
      window.clearInterval(timeRef.current)
    }
  }, [])

  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}></NavBar>
      <div className="login-form">
        <h2 className="title">账号登录</h2>

        <Form
          ref={formRef}
          onFinish={onFinish}
          autoComplete="off"
          validateTrigger={['onChange', 'onBlur']}
          initialValues={{ mobile: '13911111111', code: '246810' }}
        >
          <Form.Item
            className="login-item"
            name="mobile"
            rules={[
              { required: true, message: '手机号不能为空' },
              { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误' },
            ]}
          >
            <Input
              placeholder="请输入手机号"
              maxLength={11}
              ref={mobileRef}
            ></Input>
          </Form.Item>
          <List.Item
            className="login-code-extra"
            extra={
              <span className="code-extra" onClick={onGetCode}>
                {time === 0 ? '发送验证码' : `${time}秒后发送`}
              </span>
            }
          >
            <Form.Item
              className="login-item"
              name="code"
              rules={[
                { required: true, message: '验证码不能为空' },
                { pattern: /^\d{6}$/, message: '验证码格式错误' },
              ]}
            >
              <Input placeholder="请输入验证码" maxLength={6}></Input>
            </Form.Item>
          </List.Item>
          <Form.Item>
            <Button
              color="primary"
              type="submit"
              block
              className="login-submit"
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
